package cn.edu.nju.software.servlet.user;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.edu.nju.software.model.user.Information;
import cn.edu.nju.software.model.user.UserLoginVerifier;

/**
 * Servlet implementation class ChangePasswordServlet
 */
public class ChangePasswordServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		PrintWriter writer = response.getWriter();
		String message = "";
		String reload = "";

		request.setCharacterEncoding("UTF-8");

		String username = (String) getServletContext().getAttribute("username");

		String oldPassword = request.getParameter("oldPassword");
		UserLoginVerifier verifier = new UserLoginVerifier();
		if (verifier.verify(username, oldPassword)) {
			String newPassword = request.getParameter("newPassword");

			Information information = new Information();
			information.updatePassword(username, newPassword);
			message = "sucess!";
		} else {
			message = "password error! Check it!";
		}

		reload = "user/password.jsp";
		writer.println("<script>alert('" + message + "');"
				+ "window.location.href='" + reload + "';</script>");
	}

}
